# -*- coding: utf-8 -*-
#=============================================================================
# Koro Business Environment
# Copyright (C) 2007,2008,2010  Antonio Corroppoli
#
#This file is part of Koro BE.
# 
# Koro BE is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Koro BE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Koro BE; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#===============================================================================


#TODO:spostare la classe Table in widgets.dialogs

print 'importo panels'
#import os
import wx 
from koro.ui.wxgui.widgets import controls as co,dialogs
#from koro import PDF_VIEWER
#from koro.ui.wxgui.mellcfg import FONT_SIZE,SHOW_ID
#from koro.ui.wxgui.controls import DefaultToolBar


#===============================================================================
# TotaliManager
#===============================================================================
class TotaliManager(object):
    def __init__(self):
        self.totali=None
        
    def aggiorna_totali(self,obj=None):
        if obj is None:
            obj=self.Parent.get_object()
        obj.calcola_totali()#TODO:controllare se serve,ORA SERVE!
        self.totali.set_totale_imponibile(obj.get_totale_imponibile_fmt())
        self.totali.set_totale_iva(obj.get_totale_iva_fmt())
        self.totali.set_totale(obj.get_totale_fmt())
        self.Layout()
    
    def set_totali_ctrl(self,ctrl):
        self.totali=ctrl
    
    def get_totali_ctrl(self):
        return self.totali


#===============================================================================
# ContextManager
#===============================================================================
class ContextManager(object):
    def __init__(self):
        self._context_class=None
    
    def set_context_class(self,context_class):
        self._context_class=context_class
    
    def _get_observer(self):
        return wx.GetApp().get_observer()
    
    def _set_page_context(self):
        obs=self._get_observer()
        obs.set_context(self._context_class)
        return obs
    
    def _get_page_observer(self):
        return self._set_page_context()



#===============================================================================
# BasePanel
#===============================================================================
class BasePanel(wx.Panel):
    '''Classe Wrapper per wxPanel. Un BasePanel puo' essere una pagina di un Notebook che a sua volta 
    puo' essere contenuto in un panel e cosi' via.
    Il campo wrapper evita di scrivere self.Parent.Parent.Parent.ecc per riferirsi alla finestra 
    principale che contiene il BasePanel.
    
    Di default il parametro style vale wx.NO_BORDER|wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN.'''
    def __init__(self,parent,style=wx.NO_BORDER|wx.CLIP_CHILDREN|wx.TAB_TRAVERSAL,*args,**kwargs):
        self.wrapper=kwargs.pop('wrapper',parent)
        wx.Panel.__init__(self,parent,style=style,*args,**kwargs)
        mainsizer=wx.BoxSizer()
        self.SetSizer(mainsizer)
    
    def get_wrapper(self):
        return self.wrapper
    
    def get_contextual_observer(self):
        return self.wrapper.get_contextual_observer()
    
    def set_accelerator_table(self,*args,**kwargs):
        self.SetAcceleratorTable(wx.AcceleratorTable(*args,**kwargs))
    
    def set_main_sizer(self,sizer):
        self.Sizer.Add(sizer,0,wx.ALL|wx.EXPAND,border=10)
        self.Sizer.Layout()
    
    def reset_focus(self):
        pass


##===============================================================================
## TablePanel
##===============================================================================
#class TablePanel(wx.Panel):
#    '''Classe base per i panel delle tabelle.
#    Il costruttore chiama in ordine i metodi _init_layout_objects, _do_layout, _bind e update_fields.'''
#    def __init__(self,*args,**kwargs):
#        object=kwargs.pop('object')
#        wx.Panel.__init__(self,*args,**kwargs)
#        self._toolbar=co.TablePanelToolBar(self)
#        self.Bind(wx.EVT_TOOL, self._on_close,id=wx.ID_CLOSE)
#        self._init_layout_objects()
#        self._do_layout()        
#        self._bind()
#        self.update_fields(object)
#    
#    def _on_close(self,evt):
#        print self.__class__.__name__,'_on_close'
#        self.Parent.Close()
#    
#    def _init_layout_objects(self):
#        '''Inizializza gli oggetti che compongono il layout della finestra.
#        OVERRIDE IN SUBCLASS.'''
#        pass
#    
#    def _do_layout(self):
#        '''Definisce il layout della finestra.
#        OVERRIDE IN SUBCLASS.'''
#        pass
#    
#    def _bind(self):
#        '''Lega gli eventi della finestra ai rispettivi event handler.
#        OVERRIDE IN SUBCLASS '''
#        pass
#    
#    def update_fields(self,object):
#        '''Aggiorna i campi della finestra con i valori dell'oggetto corrente.
#        OVERRIDE IN SUBCLASS'''
#        pass
#    
#    def update_object(self):
#        '''Aggiorna l'oggetto corrente ai valori immessi dall'utente.
#        OVERRIDE IN SUBCLASS'''
#        pass


#===============================================================================
# OpzioniPanelBase
#===============================================================================
class OpzioniPanelBase(wx.Panel):
    def __init__(self,*args,**kwargs):
        wx.Panel.__init__(self,*args,**kwargs)
        self.SetSizer(wx.BoxSizer())
    
    def set_main_sizer(self,sizer):
        self.Sizer.Add(sizer,0,wx.ALL|wx.EXPAND,border=10)
        self.Sizer.Layout()
    
    def update_fields(self,opzioni):
        raise Exception('Override in subclass!')
    
    def reset_fields(self):
        raise Exception('Override in subclass!')
    
    def update_object(self,opzioni):
        raise Exception('Override in subclass!')
    
    def before_close(self,observer):
        raise Exception('{0} - Override in subclass!'.format(str(self)))
    
    def on_page_focus(self):
        raise Exception('Override in subclass!')

#------------------------------- TABELLA GENERICA ---------------------------------#
#===============================================================================
# Table
#===============================================================================
class Table(wx.Dialog):
    def __init__(self,*args,**kwargs):
        print '-debug:costruttore koro.ui.wxgui.panels.Table'
        panel=kwargs.pop('panel')
        kwargs['title']=kwargs.pop('title',panel.TITLE)
        self._object=kwargs.pop('object',None)
        wx.Dialog.__init__(self,*args,**kwargs)
        self.SetFont(wx.Font(9,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL))
        self.__bind()
        if self._object is None:
            self._object=self.Parent._request_new_object()
        self._panel=panel(self,object=self._object)
        s=wx.BoxSizer()
        s.Add(self._panel,1,wx.EXPAND|wx.ALL,border=1)
        self.SetSizer(s)
        self.SetInitialSize()
        self.SetSizeWH(780,self.GetSize().GetHeight())
        self.Bind(wx.EVT_CLOSE,self.__on_close,id=self.GetId())
        #self.Fit()
        self.Layout()
    
    def __bind(self):
        closeID=wx.NewId()
        self.Bind(wx.EVT_MENU, self.__close, id=closeID)
        at=wx.AcceleratorTable([(wx.ACCEL_NORMAL,wx.WXK_ESCAPE,closeID)])
        self.SetAcceleratorTable(at)
    
    def get_object(self):
        """Restituisce l'oggetto corrente."""
        return self._object
    
    def __close(self,evt):
        '''Genera l'evento wx.EVT_CLOSE. usato per le acceleator table.'''
        self.Close()

    def __on_close(self,evt):
        print self.__class__.__name__,'on_close'
        evt.Skip()
        if self._object.ID is None:            
            response=wx.GetApp().show_question("Salvare il documento appena creato?")
            if response==wx.ID_NO:
                self.destroy()
            elif response==wx.ID_CANCEL:
                evt.Skip(False)
            elif response==wx.ID_YES:
                self._panel.update_object()
        elif self._object.is_editable():
            self._panel.update_object()
        else:
            self._object=None
    
    def end_modal(self,code):
        self.__on_close(None)
        self.EndModal(code)            
    
    def destroy(self):
        print self.__class__.__name__,'destroy'
        self._panel=None
        self._object=None
    
    def get_contextual_observer(self):
        return self.Parent.get_page_observer()
    
    def update(self):
        self._panel.update_object()
        self._panel.update_fields(self._object)
        
    def TransferDataFromWindow(self):
        print '+++++++++++++++++++++++++++++FROM'
        
    def TransferDataToWindow(self):
        print '++++++++++++++++++++++++++++++TO'


class ObjectPanel(BasePanel):
    def __init__(self,*args,**kwargs):
        BasePanel.__init__(self, *args, **kwargs)
        self._object=None
    
    def set_object(self,obj):
        self._object=obj
    
    def show(self):
        dialog=dialogs.KoroObjectDialog(self.Parent,panel=self)
        self.update_fields()
        dialog.CenterOnScreen()
        if wx.IsBusy():
            wx.EndBusyCursor()
        return dialog.ShowModal()
    
    def get_object(self):
        return self._object
    
    
        
   
